1
'*************************** Module Header ******************************'
2 ' Module Name: MainForm.vb
4 ' Copyright (c) Microsoft Corporation.
6 ' This is the main form of this application. It is used to initialize the UI and
9 ' This source is subject to the Microsoft Public License.
10 ' See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
11 ' All other rights reserved.
13 ' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
14 ' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
15 ' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
16 '*************************************************************************'
23 Partial
Public Class MainForm
26 Private _client
As FTPClientManager
= Nothing
28 Private _currentCredentials
As NetworkCredential
= Nothing
36 #Region
"URL navigation"
39 ''' Handle the Click event of btnConnect.
41 Private Sub btnConnect_Click(ByVal sender
As Object, ByVal e
As EventArgs
) _
42 Handles btnConnect
.Click
44 ' Connect to server specified by tbFTPServer.Text.
45 Connect(Me.tbFTPServer
.Text
.Trim())
49 Private Sub Connect(ByVal urlStr
As String)
51 Dim url
As New Uri(urlStr
)
53 ' The schema of url must be ftp.
54 If Not url
.Scheme
.Equals("ftp", StringComparison
.OrdinalIgnoreCase
) Then
55 Throw
New ApplicationException("The schema of url must be ftp. ")
58 ' Set the url to the folder that contains this file.
60 url
= New Uri(url
, "..")
63 ' Show the Form UICredentialsProvider to get new Credentials.
64 Using provider
As New UICredentialsProvider(Me._currentCredentials
)
66 ' Show the Form UICredentialsProvider as a dialog.
67 Dim result
= provider
.ShowDialog()
69 ' If user typed the Credentials and pressed the "OK" button.
70 If result
= System
.Windows
.Forms
.DialogResult
.OK
Then
72 ' Reset the current Credentials.
73 Me._currentCredentials
= provider
.Credentials
80 ' Initialize the FTPClient instance.
81 _client
= New FTPClientManager(url
, _currentCredentials
)
83 AddHandler _client
.UrlChanged
, AddressOf client_UrlChanged
84 AddHandler _client
.StatusChanged
, AddressOf client_StatusChanged
85 AddHandler _client
.ErrorOccurred
, AddressOf client_ErrorOccurred
86 AddHandler _client
.FileUploadCompleted
, AddressOf client_FileUploadCompleted
87 AddHandler _client
.NewMessageArrived
, AddressOf client_NewMessageArrived
89 ' Refresh the UI and list the sub directories and files.
93 Catch webEx
As System
.Net
.WebException
94 If (TryCast(webEx
.Response
, FtpWebResponse
)).StatusCode
= FtpStatusCode
.NotLoggedIn
Then
95 ' Reconnect the server.
100 MessageBox
.Show(webEx
.Message
)
102 Catch ex
As Exception
103 MessageBox
.Show(ex
.Message
)
108 ''' Log the message of FTPClient.
110 Private Sub client_NewMessageArrived(ByVal sender
As Object, _
111 ByVal e
As NewMessageEventArg
)
112 Me.Invoke(New EventHandler(Of NewMessageEventArg
)( _
113 AddressOf client_NewMessageArrivedHandler
), sender
, e
)
116 Private Sub client_NewMessageArrivedHandler(ByVal sender
As Object, _
117 ByVal e
As NewMessageEventArg
)
118 Dim log
As String = String.Format("{0} {1}", Date.Now
, e
.NewMessage
)
119 Me.lstLog
.Items
.Add(log
)
120 Me.lstLog
.SelectedIndex
= Me.lstLog
.Items
.Count
- 1
124 ''' Log the FileUploadCompleted event when a file was uploaded.
126 Private Sub client_FileUploadCompleted(ByVal sender
As Object, _
127 ByVal e
As FileUploadCompletedEventArgs
)
128 Me.Invoke(New EventHandler(Of FileUploadCompletedEventArgs
)( _
129 AddressOf client_FileUploadCompletedHandler
), sender
, e
)
132 Private Sub client_FileUploadCompletedHandler(ByVal sender
As Object, _
133 ByVal e
As FileUploadCompletedEventArgs
)
134 Dim log
As String = String.Format( _
135 "{0} Upload from {1} to {2} is completed. Length: {3}. ", _
136 Date.Now
, e
.LocalFile
.FullName
, e
.ServerPath
, e
.LocalFile
.Length
)
138 Me.lstLog
.Items
.Add(log
)
139 Me.lstLog
.SelectedIndex
= Me.lstLog
.Items
.Count
- 1
143 ''' Log the ErrorOccurred event if there was an error.
145 Private Sub client_ErrorOccurred(ByVal sender
As Object, ByVal e
As ErrorEventArgs
)
146 Me.Invoke(New EventHandler(Of ErrorEventArgs
)( _
147 AddressOf client_ErrorOccurredHandler
), sender
, e
)
150 Private Sub client_ErrorOccurredHandler(ByVal sender
As Object, ByVal e
As ErrorEventArgs
)
151 Me.lstLog
.Items
.Add(String.Format("{0} {1} ", Date.Now
, e
.ErrorException
.Message
))
153 Dim innerException
= e
.ErrorException
.InnerException
155 ' Log all the innerException.
156 Do While innerException IsNot
Nothing
157 Me.lstLog
.Items
.Add(String.Format(vbTab
& vbTab
& vbTab
& " {0} ", _
158 innerException
.Message
))
159 innerException
= innerException
.InnerException
162 Me.lstLog
.SelectedIndex
= Me.lstLog
.Items
.Count
- 1
166 ''' Refresh the UI if the Status of the FTPClient changed.
168 Private Sub client_StatusChanged(ByVal sender
As Object, ByVal e
As EventArgs
)
169 Me.Invoke(New EventHandler(AddressOf client_StatusChangedHandler
), sender
, e
)
172 Private Sub client_StatusChangedHandler(ByVal sender
As Object, ByVal e
As EventArgs
)
175 Dim log
As String = String.Format("{0} FTPClient status changed to {1}. ", _
176 Date.Now
, _client
.Status
.ToString())
178 Me.lstLog
.Items
.Add(log
)
179 Me.lstLog
.SelectedIndex
= Me.lstLog
.Items
.Count
- 1
182 Private Sub RefreshUI()
183 ' Disable all the buttons if the client is uploading file.
184 If _client Is
Nothing OrElse _client
.Status
<> FTPClientManagerStatus
.Idle
Then
186 btnBrowseLocalFolder
.Enabled
= False
187 btnUploadFolder
.Enabled
= False
189 btnBrowseLocalFile
.Enabled
= False
190 btnUploadFile
.Enabled
= False
192 btnDelete
.Enabled
= False
194 btnNavigateParentFolder
.Enabled
= False
195 lstFileExplorer
.Enabled
= False
198 btnBrowseLocalFolder
.Enabled
= True
199 btnUploadFolder
.Enabled
= True
201 btnBrowseLocalFile
.Enabled
= True
202 btnUploadFile
.Enabled
= True
204 btnDelete
.Enabled
= True
206 btnNavigateParentFolder
.Enabled
= True
207 lstFileExplorer
.Enabled
= True
210 btnConnect
.Enabled
= _client Is
Nothing _
211 OrElse _client
.Status
= FTPClientManagerStatus
.Idle
213 RefreshSubDirectoriesAndFiles()
218 ''' Handle the UrlChanged event of the FTPClient.
220 Private Sub client_UrlChanged(ByVal sender
As Object, ByVal e
As EventArgs
)
221 Me.Invoke(New EventHandler(AddressOf client_UrlChangedHandler
), sender
, e
)
224 Private Sub client_UrlChangedHandler(ByVal sender
As Object, ByVal e
As EventArgs
)
225 RefreshSubDirectoriesAndFiles()
227 Dim log
As String = String.Format("{0} The current url changed to {1}. ", _
228 Date.Now
, _client
.Url
)
230 Me.lstLog
.Items
.Add(log
)
231 Me.lstLog
.SelectedIndex
= Me.lstLog
.Items
.Count
- 1
235 ''' Handle the DoubleClick event of lstFileExplorer.
237 Private Sub lstFileExplorer_DoubleClick(ByVal sender
As Object, ByVal e
As EventArgs
) _
238 Handles lstFileExplorer
.DoubleClick
239 ' if only one item is selected and the item represents a folder, then navigate
241 If lstFileExplorer
.SelectedItems
.Count
= 1 _
242 AndAlso (TryCast(lstFileExplorer
.SelectedItem
, FTPFileSystem
)).IsDirectory
Then
243 Me._client
.Naviagte((TryCast(lstFileExplorer
.SelectedItem
, FTPFileSystem
)).Url
)
248 ''' Handle the Click event of btnNavigateParentFolder.
250 ''' <param name="sender"></param>
251 ''' <param name="e"></param>
252 Private Sub btnNavigateParentFolder_Click(ByVal sender
As Object, ByVal e
As EventArgs
) Handles btnNavigateParentFolder
.Click
254 ' Navigate to the parent folder.
255 Me._client
.NavigateParent()
259 ''' List the sub directories and files.
261 Private Sub RefreshSubDirectoriesAndFiles()
262 If _client Is
Nothing Then
266 lbCurrentUrl
.Text
= String.Format("Current Path: {0}", _client
.Url
)
268 Dim subDirs
= _client
.GetSubDirectoriesAndFiles()
271 Dim orderedDirs
= From dir
In subDirs _
272 Order By dir
.IsDirectory Descending
, dir
.Name _
275 lstFileExplorer
.Items
.Clear()
276 For Each subdir
In orderedDirs
277 lstFileExplorer
.Items
.Add(subdir
)
284 #Region
"Upload a Folder"
287 ''' Handle the Click event of btnBrowseLocalFolder.
289 Private Sub btnBrowseLocalFolder_Click(ByVal sender
As Object, ByVal e
As EventArgs
) _
290 Handles btnBrowseLocalFolder
.Click
295 ''' Handle the Click event of btnUploadFolder.
297 Private Sub btnUploadFolder_Click(ByVal sender
As Object, ByVal e
As EventArgs
) _
298 Handles btnUploadFolder
.Click
300 ' If the tbLocalFolder.Text is empty, then show a FolderBrowserDialog.
301 If String.IsNullOrEmpty(tbLocalFolder
.Text
) _
302 AndAlso
BrowserLocalFolder() <> DialogResult
.OK
Then
307 Dim dir
As New DirectoryInfo(tbLocalFolder
.Text
)
309 If Not dir
.Exists
Then
310 Throw
New ApplicationException( _
311 String.Format(" The folder {0} does not exist!", dir
.FullName
))
314 ' Upload the selected items.
315 _client
.UploadFolder(dir
, _client
.Url
, chkCreateFolder
.Checked
)
316 Catch ex
As Exception
317 MessageBox
.Show(ex
.Message
)
322 ''' Show a FolderBrowserDialog.
324 Private Function BrowserLocalFolder() As DialogResult
325 Using folderBrowser
As New FolderBrowserDialog()
326 If Not String.IsNullOrEmpty(tbLocalFolder
.Text
) Then
327 folderBrowser
.SelectedPath
= tbLocalFolder
.Text
329 Dim result
= folderBrowser
.ShowDialog()
330 If result
= DialogResult
.OK
Then
331 tbLocalFolder
.Text
= folderBrowser
.SelectedPath
339 #Region
"Upload files"
341 Private Sub btnBrowseLocalFile_Click(ByVal sender
As Object, ByVal e
As EventArgs
) _
342 Handles btnBrowseLocalFile
.Click
346 Private Sub btnUploadFile_Click(ByVal sender
As Object, ByVal e
As EventArgs
) _
347 Handles btnUploadFile
.Click
348 If tbLocalFile
.Tag Is
Nothing AndAlso
BrowserLocalFiles() <> DialogResult
.OK
Then
353 Dim files
As New List(Of FileInfo
)()
354 Dim selectedFiles() As String = TryCast(tbLocalFile
.Tag
, String())
356 For Each selectedFile
In selectedFiles
357 Dim fileInfo_Renamed
As New FileInfo(selectedFile
)
358 If Not fileInfo_Renamed
.Exists
Then
359 Throw
New ApplicationException( _
360 String.Format(" The file {0} does not exist!", selectedFile
))
362 files
.Add(fileInfo_Renamed
)
366 If files
.Count
> 0 Then
367 _client
.UploadFoldersAndFiles(files
.Cast(Of System
.IO
.FileSystemInfo
)(), _client
.Url
)
369 Catch ex
As Exception
370 MessageBox
.Show(ex
.Message
)
375 ''' Show a FolderBrowserDialog.
377 Private Function BrowserLocalFiles() As DialogResult
378 Using fileBrowser
As New OpenFileDialog()
379 fileBrowser
.Multiselect
= True
380 Dim result
= fileBrowser
.ShowDialog()
381 If result
= DialogResult
.OK
Then
382 tbLocalFile
.Tag
= fileBrowser
.FileNames
384 Dim filesText
As New StringBuilder()
385 For Each file
In fileBrowser
.FileNames
386 filesText
.Append(file
& ";")
388 tbLocalFile
.Text
= filesText
.ToString()
397 #Region
"Delete files"
399 Private Sub btnDelete_Click(ByVal sender
As Object, ByVal e
As EventArgs
) _
400 Handles btnDelete
.Click
401 If lstFileExplorer
.SelectedItems
.Count
= 0 Then
402 MessageBox
.Show("Please select the items to delete in the FTP File Explorer")
405 Dim itemsToDelete
= _
406 lstFileExplorer
.SelectedItems
.Cast(Of FTPFileSystem
)().ToList()
408 Me._client
.DeleteItemsOnFTPServer(itemsToDelete
)